package com.strongbj.iot.devices.ru.response.handle;

import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.mq.producer.TopicSender;
import com.strongbj.iot.devices.ru.message.RUMessage;
import com.strongbj.iot.devices.ru.response.entity.AlarmInfoEntity;
import com.strongbj.iot.devices.ru.response.message.RUMQMessage;
/**
 * 报警信息的处理
 * @author yuzhantao
 *
 */
public class AlarmInfoHandle implements IMessageHandle<RUMessage,Object> {
	private static Logger logger = LogManager.getLogger(AlarmInfoHandle.class.getName());
//	private static RUResolve resolve = (RUResolve) ContextUtils.getBean("rUresolve");
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	@Override
	public boolean isHandle(RUMessage t) {
		if(t.getType()==7){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, RUMessage t) {
		String json = this.alarmInfoUpload(t);
		logger.info(json);
		topicSender.send("RU", json);
		return null;
	}

	/**
	 * 报警信息上传
	 * @param message
	 * @return
	 */
	private String alarmInfoUpload(RUMessage message) {
		AlarmInfoEntity entity = new AlarmInfoEntity();
		String address = ByteUtil.byteArrToHexString(message.getAddress());
		entity.setDevAddrCode(address);
		List<AlarmInfoEntity.U> udevInfo = new ArrayList<AlarmInfoEntity.U>();
		byte[] alarm = message.getBody();
		for (int i = 0; i < alarm.length; i=i+2) {
			int isAlarm = ByteUtil.byteToInt(alarm[i]);
			int uPostion = ByteUtil.byteToInt(alarm[i + 1]);
			if(isAlarm == 1) {
				AlarmInfoEntity.U u = entity.new U();
				u.setPosition(uPostion);
				udevInfo.add(u);
			}
		}
		entity.setUdevInfo(udevInfo);
		RUMQMessage mes = new RUMQMessage();
		mes.setActioncode("reader007");
		mes.setGUID(String.valueOf(new Date().getTime()));
		mes.setRfidtype("RU1000");
		mes.setAwsPostdata(entity);
		return JSON.toJSONString(mes); 
	}
}
